//
//  EditDetailViewController.m
//  Comma
//
//  Created by 杜远洋 on 15-1-20.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "EditDetailViewController.h"
#import "EditDetailView.h"
#import "URLMacro.h"
#import "SchoolControllerViewController.h"
#import "GlobalMethod.h"
#import "AFNetWorkingYU.h"
#import "LoginViewController.h"
#import "YRSideViewController.h"
#import "LoadIndicator.h"
#import "Reachability.h"
@interface EditDetailViewController ()<SchoolControllerViewControllerDelegate>

@end

@implementation EditDetailViewController

- (void)loadView
{
    self.edit = [[EditDetailView alloc] initWithLeftButton:@"返回" RightButton:@"保存" Title:@"详细" FooterView:FooterViewStateNone];
     self.view = self.edit;
    
    // 不能划出侧边栏
    YRSideViewController *slide = [YRSideViewController share];
    slide.needSwipeShowMenu = NO;
}

#pragma mark - 点击编辑的时候 进入的是数据库  初始的都是空值

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createMyEdit];
    [self getDataFromServer];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

#pragma mark - 为了服从MVC标准原则 我们把buttonAction切换视图放到了controller里  所以一般都要设置view为属性 改变View的控件的状态 或者 值

- (void)createMyEdit
{
    [self.edit.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.edit.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 从服务器获取数据(给所有控件初始值)
- (void)getDataFromServer
{
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    
    NSString *str =[NSString stringWithFormat:@"approveKey=%@&deviceParam=%@", device, key];
    NSString *getUrl = [NSString stringWithFormat:@"%@?%@", URL_USER_GETDETAIL, str];
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {

    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)result;
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
        if ([[dic objectForKey:@"msg"] isEqualToString:@"success"])
        {
            [LoadIndicator stopAnimationInView:self.view];
            NSDictionary *my = [dic objectForKey:@"obj"];
            for (NSString *key in my.allKeys) {
                if ([[my objectForKey:key] isKindOfClass:[NSNull class]]) {
                    [my setValue:@"" forKey:key];
                }
            }

            self.edit.myDic = my;
            
            [self.edit.schoolButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.edit.myButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.edit.sex addTarget:self action:@selector(sexSheetAction1:) forControlEvents:UIControlEventTouchUpInside];
        }
        }
        else
        {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            self.view.userInteractionEnabled = NO;
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        self.view.userInteractionEnabled = NO;
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];

    }
}


- (void)leftButtonAction:(id)sender
{
    NSLog(@"111");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightButtonAction:(id)sender
{

    [self transferMyDataToServer];
    //这个还需要修改  现在只是测试阶段  所以  跳转页面在这里写  以后要改成在数据上传服务器之后写
    
    [self.delegate transferInformation:[self getAllMyInformation]];
    [self.edit resignFirstResponder];
   
}

#pragma mark - 获取修改后的数据 传送至服务器(问题： 所有的属性都得写 都得传过来 下一次服务器请求数据的时候会从里面取，如qq等)
- (NSDictionary *)getAllMyInformation
{
    self.myDic = [NSMutableDictionary dictionary];
    
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    [self.myDic setObject:key forKey:@"deviceParam"];
    [self.myDic setObject:device forKey:@"approveKey"];
    [self.myDic setObject:self.edit.name.text forKey:@"nick"];
    [self.myDic setObject:self.edit.shortIntroduction.text forKey:@"profile"];
    [self.myDic setObject:self.edit.department.text forKey:@"dept"];
    [self.myDic setObject:self.edit.major.text forKey:@"major"];
    [self.myDic setObject:self.edit.qq.text forKey:@"qq"];
    [self.myDic setObject:self.edit.studentNumber.text forKey:@"sNum"];
    [self.myDic setObject:self.edit.specialty.text forKey:@"speciality"];
    [self.myDic setObject:self.edit.interest.text forKey:@"interest"];
    
    // duibutton 进行设置    因为button的title不能为空
    if (self.edit.sex.currentTitle == nil || self.edit.sex.currentTitle.length == 0) {
    }
    else
    {
        [self.myDic setObject:self.edit.sex.currentTitle forKey:@"gender"];
    }
    
    
    if (self.edit.schoolButton.currentTitle == nil || self.edit.schoolButton.currentTitle.length == 0) {
    }
    else
    {
        [self.myDic setObject:self.edit.schoolButton.currentTitle forKey:@"school"];
    }
    
    
    if (self.edit.grade.currentTitle == nil || self.edit.grade.currentTitle.length == 0) {
    }
    else
    {
        [self.myDic setObject:self.edit.grade.currentTitle forKey:@"grade"];
    }
    
    
    if (self.edit.birthday.currentTitle == nil || self.edit.birthday.currentTitle.length == 0) {
    }
    else
    {
        [self.myDic setObject:self.edit.birthday.currentTitle forKey:@"birth"];
       
    }
    
    return self.myDic;
}
#pragma mark - 传给服务器数据(点击保存时会调用)
- (void)transferMyDataToServer
{
    //添加覆盖视图
//    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    [myView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.4]];
//    [self.view addSubview:myView];
//    
//    UILabel *showView = [[UILabel alloc] initWithFrame:CGRectMake(200, 200, 200, 80)];
//    [showView setText:@"正在上传服务器，请稍后.."];
//    showView.center = myView.center;
//    [showView setBackgroundColor:[UIColor whiteColor]];
//    [myView addSubview:showView];
    NSString *myTitle = @"正在上传服务器";
    NSString *myMsg = @"请稍后..";
    UIAlertView * alert= [[UIAlertView alloc] initWithTitle:myTitle message:myMsg delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    
    
    
    NSString *str = [self getMyParametersOfUrl];
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {
        
    [AFNetWorkingYU netWorkWithURL:URL_USER_INFO_EDIT body:str resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
        
        //此时应该插入一个动画 “正在同步服务器，请稍后” ,返回结果显示是否修改成功
//        [myView removeFromSuperview];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1.5];
        if ([str isEqualToString:@"编辑成功！"]) {
           
            [self showTheResult:@"编辑成功！" msg:nil];
        }
        else
        {
            [self showTheResult:@"修改失败" msg:@"未登录,或登录已过期"];
        }
            
        }
        else
        {
            //添加无网图
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            self.view.userInteractionEnabled = NO;
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
       
    }];
    }
    else
    {
        //添加无网图
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        self.view.userInteractionEnabled = NO;
        [fondView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];

    }

    
}

#pragma mark - 显示信息保存的状态 是否保存成功
- (void)showTheResult:(NSString *)title msg:(NSString *)msg
{
    if (IOS_VERSION >= 8.0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(dismissMyAlert) withObject:alert afterDelay:3];
    }
    else
    {
        UIAlertView * alert= [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:3];
    }
    
}
- (void)dismissMyAlert
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)dismissAlert:(UIAlertView *)alert
{
    if(alert){
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
        
    }
    
    
}
#pragma mark - 拼接我们所需要的网址  字典在上面
- (NSString *)getMyParametersOfUrl
{
    NSString *str = @"";
    NSDictionary *parametersData = [self getAllMyInformation];
    for (NSString *key in parametersData) {
        if ([str length] == 0 || [str isEqualToString:@""]) {
            str = [NSString stringWithFormat:@"%@=%@", key, [parametersData objectForKey:key]];
        }
        else
        {
            str = [NSString stringWithFormat:@"%@&%@=%@", str, key, [parametersData objectForKey:key]];
        }
    }
    
    return str;
}


#pragma mark - 学校的跳转界面action
- (void)buttonAction:(id)sender
{
    [self.edit endEditing:YES];
    SchoolControllerViewController *school = [[SchoolControllerViewController alloc] init];
    school.delegate = self;
    [self presentViewController:school animated:YES completion:nil];
}
#pragma mark - 从学校叶面的数据里 得到学校的名字 传过来 并赋值给view的控件
- (void)transferData:(NSString *)schoolName
{
  
    self.edit.schoolButton.titleLabel.text = schoolName;
    [self.edit.schoolButton setTitle:schoolName forState:UIControlStateNormal];
    NSLog(@"%@",self.edit.schoolButton.titleLabel.text);

    
}

#pragma mark - 调用性别的actionsheet（选择性别）
- (void)sexSheetAction1:(id)sender
{
    if (IOS_VERSION >= 8.0) {
        UIAlertController *sex = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *boy = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self chooseBoy];
        }];
        UIAlertAction *girl = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self chooseGirl];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [self clickCancel];
        }];
        [sex addAction:boy];
        [sex addAction:girl];
        [sex addAction:cancel];
        [self presentViewController:sex animated:YES completion:nil];
    }
    else
    {
        self.sexSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男", @"女",nil];
        
        [self.sexSheet showInView:self.view];
        
    }
    

}
#pragma mark - 在iOS8之后用
- (void)chooseBoy
{
    [self.edit.sex setTitle:@"男" forState:UIControlStateNormal];
}
- (void)chooseGirl
{
    [self.edit.sex setTitle:@"女" forState:UIControlStateNormal];
}
- (void)clickCancel
{
    return;
}

#pragma mark - 在iOS8之前用
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        [self.edit.sex setTitle:@"男" forState:UIControlStateNormal];
    }
    else if(buttonIndex == 1)
    {
        [self.edit.sex setTitle:@"女" forState:UIControlStateNormal];
    }
    else
    {
        return;
    }
}



- (void)viewWillAppear:(BOOL)animated
{
    if (!self.edit) {
        [LoadIndicator addIndicatorInView:self.view];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
